import os, sys

from .translation_service import TranslationService

import gobject
import gtk

import translator

gobject.threads_init()

builder_file = os.path.join(os.path.split(__file__)[0], 'main_window.builder')

class MainWindow(object):
    def __init__(self):
        '''
        In this init we are going to display the main
        serverinfo window
        '''

        self.builder = gtk.Builder()
        self.builder.add_from_file(builder_file)

        self.main_window = self.builder.get_object('main_window')
        self.main_window.connect("delete-event", self.handle_delete_event)
        self.main_window.connect("destroy", self.destroy)

        self.initialize_actions()
        self.initialize_tree_view()
        self.initialize_language_selectors()
        self.connect_signals()

        self.translation_service = TranslationService()

        self.main_window.show()

        gobject.timeout_add(50, lambda : self.check_for_results())

    def destroy(self, evt):
        gtk.main_quit()

    def connect_signals(self):
        signals = {
            'on_open_action_activate' : self.on_open_action_activate,
            'on_paste_action_activate' : self.on_paste_action_activate,
            'on_quit_action_activate' : self.on_quit_action_activate,
            }
        
        self.builder.connect_signals(signals)

    def initialize_actions(self):
        accelgroup = gtk.AccelGroup()
        self.main_window.add_accel_group(accelgroup)
        
        actiongroup = self.builder.get_object('BasicActions')

        # Open action
        self.open_action = self.builder.get_object('open_action')
        self.open_action.set_accel_group(accelgroup)
        actiongroup.add_action_with_accel(self.open_action, '<Control>o')
        self.open_action.connect_accelerator()

        # Paste action
        self.paste_action = self.builder.get_object('paste_action')
        self.paste_action.set_accel_group(accelgroup)
        actiongroup.add_action_with_accel(self.paste_action, '<Control>v')
        self.paste_action.connect_accelerator()

        # Quit action
        self.quit_action = self.builder.get_object('quit_action')
        self.quit_action.set_accel_group(accelgroup)
        actiongroup.add_action_with_accel(self.quit_action, '<Control>q')
        self.quit_action.connect_accelerator()

    def initialize_tree_view(self):
        self.tree_view = self.builder.get_object('tree_view')

        self.tree_view.set_rules_hint(True)

        cell = gtk.CellRendererText()
        column = gtk.TreeViewColumn('Text', cell)
        column.add_attribute(cell, 'text', 0)
        self.tree_view.append_column(column)

        self.model = self.tree_view.get_model()

    def initialize_language_selectors(self):
        self.to_lang_combo = self.builder.get_object('to_lang_combo')
        self.from_lang_combo = self.builder.get_object('from_lang_combo')

        # The combos share a model
        lang_model = self.to_lang_combo.get_model()

        langs = translator.languages.keys()
        langs.remove('UNKNOWN')
        langs.sort()

        lang_model.append(('UNKNOWN',
                           translator.languages['UNKNOWN'][0],
                           '<Auto-detect>'))
        
        for lang in langs:
            lang_model.append((lang,
                               translator.languages[lang][0],
                               translator.languages[lang][1]))

        self.to_lang_combo.set_active(langs.index('ENGLISH'))
        self.from_lang_combo.set_active(0)

    def open_file(self, filename):
        with open(filename, 'r') as f:
            self.set_text(f.read())

    def set_text(self, text):
        self.model.clear()

        from_iter = self.from_lang_combo.get_active_iter()
        from_lang = self.from_lang_combo.get_model().get_value(from_iter, 0)

        to_iter = self.to_lang_combo.get_active_iter()
        to_lang = self.to_lang_combo.get_model().get_value(to_iter, 0)
        
        self.translation_service.translate(text, from_lang, to_lang)

    def on_open_action_activate(self, action):
        dlg = gtk.FileChooserDialog("Open..",
                                    None,
                                    gtk.FILE_CHOOSER_ACTION_OPEN,
                                    (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                                     gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        dlg.set_default_response(gtk.RESPONSE_OK)
        
        rsp = dlg.run()
        filename = dlg.get_filename()
        dlg.destroy()
        if rsp == gtk.RESPONSE_OK:
            self.open_file(filename)
        
    def on_paste_action_activate(self, action):
        cb = gtk.Clipboard(selection="PRIMARY")
        data = cb.wait_for_text()
        if data is not None:
            self.set_text(data)

    def on_quit_action_activate(self, action):
        self.destroy(None)

    def check_for_results(self):
        if self.translation_service.has_data():
            src,dest = self.translation_service.get_result()
            self.model.append((src,))
            self.model.append((dest,))
        return True

    def handle_delete_event(self, widget, event, data=None):
        return False

if __name__ == '__main__':
    main()
